<template>
  <div class="wrapper-login">
    <!-- 登录表单 -->
    <div class="wrapper-form">
      <div class="wrapper-title">
        <img src="@/assets/image/logo.png" height="80" />
        <h3> 信州区卫健委工作任务管理系统 </h3>
      </div>
      <el-form ref="refForm" :model="formData" class="form-login" auto-complete="on" label-position="left">
        <el-form-item prop="username">
          <el-col :span="18" :offset="3">
            <el-input
              class="test"
              ref="refUsername"
              v-model="formData.Username"
              placeholder="请输入用户名..."
              tabindex="1"
              auto-complete="on"
              prefix-icon="User"
              maxlength="20"
              size="large"
            />
          </el-col>
        </el-form-item>

        <el-form-item prop="password">
          <el-col :span="18" :offset="3">
            <el-input
              ref="refPassword"
              :type="passwordType"
              :key="passwordType"
              v-model="formData.Password"
              placeholder="请输入密码..."
              tabindex="2"
              prefix-icon="Lock"
              maxlength="20"
              show-password
              size="large"
              @keyup="checkCapslock"
              @keyup.enter="onLogin"
              @blur="flagCaps = false"
            />
          </el-col>
        </el-form-item>

        <el-form-item class="form-option">
          <el-col :span="18" :offset="3">
            <el-row align="top">
              <el-col :span="11">
                <el-checkbox v-model="formData.IsRememberMe" label="是否记住登录状态？ " />
              </el-col>
              <el-col :span="13">
                <a href="#">忘记密码？</a>
              </el-col>
            </el-row>
          </el-col>
        </el-form-item>

        <el-form-item class="form-button">
          <el-col :span="18" :offset="3">
            <el-button :loading="flagLoading" type="primary" @click="onLogin">登录</el-button>
          </el-col>
        </el-form-item>
      </el-form>
    </div>
    <!-- 版权信息 -->
    <div class="wrapper-copyright"> &copy; 信州区卫健委 版权所有 2024 </div>
  </div>
</template>

<script>
import { getIpInner } from '@/utils/ip'
import { getSStorageObj } from '@/utils/web-storage'
import { getCookieUsername, setCookieUsername, getCookiePassword, setCookiePassword } from '@/utils/cookie'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted, onUnmounted, watch } from 'vue'
import { toastError } from '@/utils/toast'
export default defineComponent({
  name: 'LoginView',
  setup() {
    const refForm = ref(null)
    const refUsername = ref(null)
    const refPassword = ref(null)
    const formData = ref({
      Username: '',
      Password: '',
      ValidateCode: '',
      IsRememberMe: false,
      IpInner: '',
      IpOuter: '',
    })
    const flagLoading = ref(false)
    const passwordType = ref('password')
    const flagCaps = ref(false)
    const redirect = ref(undefined)
    const otherQuery = ref({})
    const currentRoute = ref(router.currentRoute.value)

    const keyDown = (e) => {
      if (e.keyCode == 13) {
        onLogin()
      }
    }
    // 重置所有登录相关信息、并清空表单
    const resetAll = () => {
      // 执行logout，清除cookie，storage，store中数据
      store.dispatch('sys_admin/logout')
      formData.value.Username === ''
      formData.value.Password === ''
      formData.value.IsRememberMe = false
    }
    // 输入密码时，检测键盘的大写键（CapsLock）是否按下
    const checkCapslock = ({ shiftKey, key } = {}) => {
      if (key && key.length === 1) {
        if ((shiftKey && key >= 'a' && key <= 'z') || (!shiftKey && key >= 'A' && key <= 'Z')) {
          flagCaps.value = true
        } else {
          flagCaps.value = false
        }
      }
      if (key === 'CapsLock' && flagCaps.value === true) {
        flagCaps.value = false
      }
    }

    // 进入登录页面时尝试从cookie中读取账号密码实现自动登录
    const autoLogin = () => {
      const username = getCookieUsername()
      const password = getCookiePassword()
      // 如果cookie中不存在账号密码，不执行自动登录
      if (!(username && password)) {
        resetAll()
        return
      }
      // 执行到了这里，说明cookie中存在账号密码，尝试自动登录
      formData.value = {
        Username: username,
        Password: password,
        ValidateCode: '',
        IsRememberMe: true,
      }
      getIpIn()
      getIpOut()
      flagLoading.value = true
      store
        .dispatch('sys_admin/login', formData.value)
        .then(() => {
          flagLoading.value = false
          // 登录成功，跳转到根目录
          router.push({ path: '/home' })
          // router.push({
          //   path: redirect.value || '/',
          //   query: otherQuery.value,
          // })
        })
        .catch(() => {
          flagLoading.value = false
          // 登录失败，重置数据
          resetAll()
        })
    }
    // 点击登录按钮执行登录
    const onLogin = () => {
      flagLoading.value = true
      getIpIn()
      getIpOut()
      store
        .dispatch('sys_admin/login', formData.value)
        .then(() => {
          flagLoading.value = false
          // 登录成功，如果勾选了自动登录，则设置cookie
          // storage 和 store 内数据已在 store/sys_admin/login 方法中完成
          if (formData.value.IsRememberMe) {
            setCookieUsername(formData.value.Username)
            setCookiePassword(formData.value.Password)
          }
          // 跳转到根目录或者从哪来回哪去
          router.push({ path: '/home' })
          // router.push({
          //   path: redirect.value || '/',
          //   query: otherQuery.value,
          // })
        })
        .catch((error) => {
          flagLoading.value = false
          toastError(error)
          console.log('error:', error)
          // 登录失败，重置数据
          resetAll()
        })
    }

    const getIpIn = () => {
      getIpInner((ip) => {
        formData.value.IpInner = ip
      })
    }
    const getIpOut = () => {
      const objIP = getSStorageObj('IPOut')
      if (objIP) {
        // 'ip': '220.176.196.203',
        // 'pro': '江西省',
        // 'proCode': '360000',
        // 'city': '上饶市',
        // 'cityCode': '361100',
        // 'region': '',
        // 'regionCode': '0',
        // 'addr': '江西省上饶市 电信ADSL',
        // 'regionNames': '',
        // 'err': '',
        formData.value.IpOuter = objIP.ip
      } else formData.value.IpOuter = ''
    }
    const getOtherQuery = (query) => {
      // Object.keys https://www.cnblogs.com/llcdxh/p/9476347.html
      // reduce https://www.cnblogs.com/amujoe/p/11376940.html
      const arr = Object.keys(query)
      return arr.reduce((prev, current) => {
        if (prev !== 'redirect') {
          prev[current] = query[current]
        }
        return prev
      }, {})
    }

    onMounted(() => {
      autoLogin()
      window.addEventListener('keydown', keyDown)
    })

    onUnmounted(() => {
      window.removeEventListener('keydown', keyDown, false)
    })

    watch(currentRoute, (newValue, oldValue) => {
      console.log('oldValue', oldValue)
      console.log('newValue', newValue)
      const query = currentRoute.value.query
      if (query) {
        redirect.value = query.redirect
        otherQuery.value = getOtherQuery(query)
      }
    })

    return {
      refForm,
      refUsername,
      refPassword,
      formData,
      flagLoading,
      passwordType,
      flagCaps,
      redirect,
      otherQuery,
      keyDown,
      resetAll,
      checkCapslock,
      autoLogin,
      onLogin,
      getIpIn,
      getIpOut,
      getOtherQuery,
    }
  },
})
</script>

<style lang="scss" scoped>
.wrapper-login {
  padding-top: 120px;
  width: 100%;
  height: 100%;
  background: url('@/assets/image/bg_login.jpg') no-repeat;
  background-size: 100% 100%;
  background-attachment: fixed;
  .wrapper-form {
    width: 480px;
    max-width: 480px;
    margin: 0 auto 0 auto;
    background: #00000050;
    border: 12px solid #ffffff30;
    border-radius: 10px;
    .wrapper-title {
      margin: 30px 0;
      text-align: center;
      h3 {
        margin-top: 12px;
        font-size: 20px;
        color: #ffffff;
        text-align: center;
        font-weight: bold;
      }
    }
    .form-login {
      background: transparent;
      .el-form-item {
        .el-input {
          :deep(.el-input__wrapper) {
            background: none;
            border: none;
            box-shadow: inset 1px 1px 5px 0 #00000030;
            // box-shadow:阴影类型 X轴位移 Y轴位移 阴影大小 阴影扩展 阴影颜色
            // 当不设阴影类型时，默认为投影效果。当设为inset时，为内阴影效果。
            .el-input__inner {
              color: #ffffff;
              background: none;
              background-color: transparent !important;
            }
          }
          :deep(.el-input__wrapper.is-focus) {
            box-shadow: inset 1px 1px 5px 0 #00000060;
          }
        }
        .el-checkbox {
          color: #ffffff;
        }
      }
      .form-option {
        a {
          color: #ffffff;
        }
      }
      .form-button {
        button {
          width: 100%;
        }
      }
    }
  }
  .wrapper-copyright {
    background: transparent;
    margin: 20px auto 0 auto;
    font-size: 14px;
    text-align: center;
  }
}
</style>
